//
//  ViewController.m
//  彩票
//
//  Created by 冀柳冲 on 2017/8/15.
//  Copyright © 2017年 冀柳冲. All rights reserved.
//



//获取关注的人
#define Concern_URL @"authedUserId=8201706011578588&currentPage=1&loginKey=JCZJ_LOGIN20170706215036&service=USER_ATTENTIONS_INFO&userId=8201706011578588&sign=73ad90619f69f53334f90b2f9875ee37"

#import "UserCell.h"
#import "UserInfo.h"
#import "ViewController.h"
#import "MYDanViewController.h"
#import <PYSearch/PYSearchSuggestionViewController.h>
#import "FilterViewController.h"
#import "DanZi.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,PYSearchViewControllerDelegate,PYSearchSuggestionViewDataSource>
@property(nonatomic,strong) UITableView * tableView;
@property(nonatomic,strong) NSMutableArray * dataSource;

@property(nonatomic,strong) MJRefreshNormalHeader * header;
@property(nonatomic,strong) MJRefreshBackNormalFooter * footer;

@property(nonatomic,strong) NSMutableArray * tempArray;

@property(nonatomic,strong) PYSearchSuggestionViewController * suggestionVC;
@property(nonatomic,strong) UserInfo * resultModel;

@property(nonatomic,strong) NSMutableArray * filters;

@property(nonatomic,strong) NSMutableArray * allDatas;

@end

static NSInteger page = 1;



@implementation ViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    @weakify(self)
    _header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        page = 1;
        [self loadData];
    }];
    // [_header beginRefreshing];
    
    _footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        page++;
        [self loadMoreData:page];

    }];
    
    [self setupUI];
    
    [_header beginRefreshing];
    
    self.navigationItem.title = @"跟单列表";
}





- (void)setupUI{
    _tempArray = [NSMutableArray array];
    self.dataSource = [NSMutableArray array];
    self.filters = [NSMutableArray array];
    self.allDatas = [NSMutableArray array];

    self.tableView.mj_header = _header;
    self.tableView.mj_footer = _footer;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, KviewWidth*3/2, NavigationBarHeight*2/3)];
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = white_color;
    label.text = @"search";
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = clear_color;
    ViewBorderRadius(label, 10, 1, white_color);
    label.userInteractionEnabled = YES;
    //self.navigationItem.titleView = label;
    UITapGestureRecognizer *tap = [UITapGestureRecognizer new];
    [label addGestureRecognizer:tap];
    @weakify(self)
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        @strongify(self)
        
        // 1.创建热门搜索
        NSArray *hotSeaches = @[@"我就一个女朋友",@"sunny冲哥",@""];
        // 2. 创建控制器
        PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:hotSeaches searchBarPlaceholder:@"输入类别或关键字" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
            // 开始搜索执行以下代码
            // 如：跳转到指定控制器
            //[searchViewController.navigationController pushViewController:[[PYTempViewController alloc] init] animated:YES];
            if (searchText.length < 1 || searchText == nil) {
                return ;
            }
            //
            
            
            //搜索获取userID;
            [NewNetWorkManager requestGETWithURLString:[NSString stringWithFormat:@"%@?authedUserId=8201706011578588&loginKey=JCZJ_LOGIN20170706215036&loginName=%@&queryExtra=1&service=USER_INFO_QUERY&sign=57c47a4265ca904a4d310902c49e693a",Base_URL,[searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] parDic:nil finish:^(id responseObject) {
                
                NSDictionary *dict = responseObject[@"response"];
               
//                UserInfo *model = [UserInfo new];
//                [model setValuesForKeysWithDictionary:dict];
//                model.userName = dict[@"loginName"];
//                self.resultModel = model;
//                [self.suggestionVC.tableView reloadData];
                
                NSLog(@"%@",responseObject);
            } conError:^(NSError *error) {
                
            }];
            
            
            
        }];
        // 3. 设置风格
        searchViewController.hotSearchStyle = PYSearchHistoryStyleARCBorderTag; // 热门搜索风格为默认
        //searchViewController.searchBarBackgroundColor = [UIColor whiteColor];
        searchViewController.searchHistoryStyle = PYSearchHistoryStyleColorfulTag; // 搜索历史风格根据选择
        
        //
        //[searchViewController.searchSuggestionView registerNib:[UINib nibWithNibName:NSStringFromClass([UserCell class]) bundle:nil] forCellReuseIdentifier:@"suggestioncell"];
        searchViewController.searchResultShowMode = PYSearchResultShowModePush;
        self.suggestionVC = [PYSearchSuggestionViewController searchSuggestionViewControllerWithDidSelectCellBlock:^(UITableViewCell *selectedCell) {
            
            //跳转到详情
            MYDanViewController *VC = [MYDanViewController new];
            UserInfo *model = ((UserCell *)selectedCell).model;
            //VC.userid = model.userId;
            [self.suggestionVC.navigationController pushViewController:VC animated:YES];
            
        }];
        self.suggestionVC.edgesForExtendedLayout = UIRectEdgeNone;
        self.suggestionVC.automaticallyAdjustsScrollViewInsets = YES;
        self.suggestionVC.dataSource = self;
        [_suggestionVC.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([UserCell class]) bundle:nil] forCellReuseIdentifier:@"usercell"];
        searchViewController.searchResultController = (UIViewController *)self.suggestionVC;
        
        // 4. 设置代理
        searchViewController.delegate = self;
        // 5. 跳转到搜索控制器
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchViewController];
        nav.navigationBar.tintColor = [UIColor whiteColor];
        nav.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        [self presentViewController:nav  animated:NO completion:nil];
        
        
        
        
        
    }];
    
}


#pragma mark  搜索代理


/** 点击(开始)搜索时调用 */
- (void)searchViewController:(PYSearchViewController *)searchViewController didSearchWithsearchBar:(UISearchBar *)searchBar searchText:(NSString *)searchText{
    
   
    

    
}

/** 点击热门搜索时调用，如果实现该代理方法则点击热门搜索时searchViewController:didSearchWithsearchBar:searchText:失效*/
- (void)searchViewController:(PYSearchViewController *)searchViewController didSelectHotSearchAtIndex:(NSInteger)index searchText:(NSString *)searchText{
    
   
    

}
/** 点击搜索历史时调用，如果实现该代理方法则搜索历史时searchViewController:didSearchWithsearchBar:searchText:失效 */
- (void)searchViewController:(PYSearchViewController *)searchViewController didSelectSearchHistoryAtIndex:(NSInteger)index searchText:(NSString *)searchText{
    
  
    

}



- (UITableViewCell *)searchSuggestionView:(UITableView *)searchSuggestionView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UserCell *cell = [searchSuggestionView dequeueReusableCellWithIdentifier:@"usercell"];
    cell.model = self.resultModel;
    
    __weak UserCell * weakCell = cell;
    
 

    
    return cell;
}
- (NSInteger)searchSuggestionView:(UITableView *)searchSuggestionView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)searchSuggestionView:(UITableView *)searchSuggestionView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}





- (IBAction)buttonClick:(id)sender{
    
    
    for (UserInfo *model in self.tempArray) {
        
        [self.dataSource removeObject:model];
    }
    NSSet *set = [NSSet setWithArray:self.dataSource];
    NSArray *sortDesc = @[[[NSSortDescriptor alloc] initWithKey:@"totalPrizeFee" ascending:YES]];
    NSArray *sortSetArray = [set sortedArrayUsingDescriptors:sortDesc];
    self.allDatas = (NSMutableArray *)sortSetArray;
    [self.tableView reloadData];
    
}




- (void)loadMoreData:(NSInteger)currentpage{
    
   
    [NewNetWorkManager requestGETWithURLString:[NSString stringWithFormat:@"%@?authedUserId=8201711152341828&currentPage=%ld&loginKey=LOGIN_20171205220734&roleName=sunny&service=PURCHASE_ORDER_JOINABLE_QUERY&&sign=c06ead48973cfef1d968a7bff93ed7f1",Base_URL,(long)currentpage] parDic:nil finish:^(id responseObject) {
        NSArray *array = responseObject[@"response"][@"normalPurchaseOrders"];
        if (array.count < 1) {
            return ;
        }
        for (NSDictionary *dic in array) {
            UserInfo *model = [UserInfo new];
            [model setValuesForKeysWithDictionary:dic];
            
            if (![self.tempArray containsObject:model.ownerUserId])
            [self.dataSource addObject:model];
            [self.tempArray addObject:model.ownerUserId];
        }
        [ self.dataSource sortUsingComparator:^NSComparisonResult(UserInfo *  _Nonnull obj1, UserInfo *  _Nonnull obj2) {
            if (obj1.totalFee > obj2.totalFee) {
                return NSOrderedAscending;
            }
            if (obj1.totalFee < obj2.totalFee) {
                return NSOrderedDescending;
            }
            return NSOrderedSame;
        }];
        [self.tableView reloadData];
        [self.footer endRefreshing];
        //[QMUITips showInfo:@"加载成功" inView:self.view hideAfterDelay:2];
    } conError:^(NSError *error) {
        [self.footer endRefreshing];
        [QMUITips showError:@"网络错误" inView:[UIApplication sharedApplication].keyWindow hideAfterDelay:2];
        
    }];

}

- (void)loadData{
    [NewNetWorkManager requestGETWithURLString:[NSString stringWithFormat:@"%@?authedUserId=8201711152341828&currentPage=%ld&loginKey=LOGIN_20171205220734&roleName=sunny&service=PURCHASE_ORDER_JOINABLE_QUERY&&sign=c06ead48973cfef1d968a7bff93ed7f1",Base_URL,(long)page] parDic:nil finish:^(id responseObject) {
        [self.dataSource removeAllObjects];
        [self.tempArray removeAllObjects];
        NSArray *array = responseObject[@"response"][@"normalPurchaseOrders"];
        if (array.count < 1) {
            return ;
        }
        for (NSDictionary *dic in array) {
            UserInfo *model = [UserInfo new];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataSource addObject:model];
            [self.tempArray addObject:model.ownerUserId];
        }
        [ self.dataSource sortUsingComparator:^NSComparisonResult(UserInfo *  _Nonnull obj1, UserInfo *  _Nonnull obj2) {
            if (obj1.totalFee > obj2.totalFee) {
                return NSOrderedAscending;
            }
            if (obj1.totalFee < obj2.totalFee) {
                return NSOrderedDescending;
            }
            return NSOrderedSame;
        }];
        [self.tableView reloadData];
        [QMUITips showInfo:@"加载成功" inView:[UIApplication sharedApplication].keyWindow hideAfterDelay:2] ;

        [self.header endRefreshing];
    } conError:^(NSError *error) {
        [self.header endRefreshing];
        [QMUITips showError:@"网络错误" inView:[UIApplication sharedApplication].keyWindow hideAfterDelay:2];

    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark--UITableViewDelegate

//row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
//header height
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}
//footer height
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
// view--header
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
// view-footer
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return [UIView new];
}
#pragma mark--UITableViewDataSource
//row 个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

//section 个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
//自定义cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UserCell *cell = [tableView dequeueReusableCellWithIdentifier:@"usercell"];
    cell.model = self.dataSource[indexPath.row];
    
    
    
    return cell;
}

#pragma mark - 点击跳转方法

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MYDanViewController *VC = [MYDanViewController new];
    UserInfo *model = self.dataSource[indexPath.row];
    VC.userid = model.ownerUserId;
    VC.purchaseNo = model.purchaseNo;
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - lazy load

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,  0, KviewWidth, KviewHeight-20) style:UITableViewStylePlain];
        
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.separatorColor = [UIColor lightGrayColor];
        _tableView.separatorInset = UIEdgeInsetsMake(0, 13, 0, 0);
        _tableView.tableFooterView = [UIView new];
        _tableView.estimatedRowHeight = 50;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([UserCell class]) bundle:nil] forCellReuseIdentifier:@"usercell"];
        [self.view addSubview:_tableView];
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    return _tableView;
}


@end
